package me.zk.practice1.list;

import java.util.HashMap;
import java.util.Map;

/**
 * 最近最少使用，每次get数据后应该把数据放到最前面
 * @Author: zhang kai
 * @Date: 2021/12/29
 * @Description:
 */
public class LRUCache  {
    private int size;
    private int capacity;
    private Node first;
    private Node last;
    private Map<Integer, Node> hashMap = null;
    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        this.hashMap = new HashMap<>(capacity);
        first = new Node();
        last = new Node();
        first.next = last;
        last.pre = first;
    }

    public int get(int key) {
        Node node = hashMap.get(key);
        if (node == null) {
            return -1;
        }
        moveToHead(node);
        return node.value;
    }

    public void put(int key, int value) {
        Node node = hashMap.get(key);
        if (node == null) {
            node = new Node(key,value);
            hashMap.put(key,node);
            addFirst(node);
            ++size;
            if (size > capacity) {
                // 删除哈希表中对应的项
                Node tail = removeTail();
                hashMap.remove(tail.key);
                --size;
            }
        } else {
            node.value = value;
            moveToHead(node);
        }

    }
    private void moveToHead(Node node) {
        removeNode(node);
        addFirst(node);
    }

    public void removeNode(Node node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
        node.next = null;
        node.pre = null;
    }
    private Node removeTail() {
        Node res = last.pre;
        removeNode(res);
        return res;
    }
    private void addFirst(Node node) {
        node.pre = first;
        node.next = first.next;
        first.next.pre = node;
        first.next = node;
    }
    static class Node{
        Node pre;
        Node next;
        int value;
        int key;
        Node(){}
        Node (int key, int value) {
            this.value = value;
            this.key = key;
        }
    }
}
